package cn.baddonkey.photography.agent.controller;

import cn.baddonkey.photography.agent.core.PlatformResponse;
import cn.baddonkey.photography.agent.utils.IpUtils;
import cn.hutool.core.util.StrUtil;

import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;

import io.swagger.v3.oas.annotations.Operation;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @PostMapping({"/getBlockPuzzleCaptcha"})
    @Operation(summary = "获得滑块验证码", description = "获得滑块验证码", method = "POST")
    public PlatformResponse get(@RequestBody CaptchaVO data, HttpServletRequest request) {
        assert request.getRemoteHost() != null;
        data.setBrowserInfo(getRemoteId(request));
        ResponseModel response = captchaService.get(data);
        return PlatformResponse.ok(response);
    }

    @PostMapping("/checkBlockPuzzleCaptcha")
    @Operation(summary = "校验滑块验证码", description = "校验滑块验证码", method = "POST")
    public PlatformResponse check(@RequestBody CaptchaVO data, HttpServletRequest request) {
        data.setBrowserInfo(getRemoteId(request));
        ResponseModel check = captchaService.check(data);
        return PlatformResponse.ok(check);
    }

    public static String getRemoteId(HttpServletRequest request) {
        String ip = IpUtils.getIpAddr(request);
        String ua = request.getHeader("user-agent");
        if (StrUtil.isNotBlank(ip)) {
            return ip + ua;
        }
        return request.getRemoteAddr() + ua;
    }
}
